package com.mlxg.master.service.impl;/**
 * @author zcy
 * @date 2025/5/23 9:50
 */

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mlxg.master.domain.HzProductSeries;
import com.mlxg.master.mapper.HzProductSeriesMapper;
import com.mlxg.master.service.IHzProductSeriesService;
import com.mlxg.selver.domain.HzProductSeriesSlave;
import com.mlxg.selver.domain.HzProductServicesIdMapping;
import com.mlxg.selver.domain.IdMapping;
import com.mlxg.selver.service.IHzProductSeriesSlaveService;
import com.mlxg.selver.service.IHzProductServicesIdMappingService;
import com.mlxg.selver.service.IIdMappingService;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zcy
 * @date 2025/5/23 9:50
 * @description: 自定义产品维护
 */
@Slf4j
@Service
@DS("master")
public class HzProductSeriesServiceImpl extends ServiceImpl<HzProductSeriesMapper, HzProductSeries> implements IHzProductSeriesService {
    @Autowired
    private IHzProductSeriesSlaveService hzProductSeriesSlaveService;

    @Autowired
    private IIdMappingService iIdMappingService;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private HzProductSeriesMapper hzProductSeriesMapper;

    @Autowired
    private IHzProductServicesIdMappingService hzProductServicesIdMappingService;

    /**
     * 自定产品维护迁移方法
     */
    @Override
    public void transferProductSeries() {
        int pageSize = 1000;
        int pageNum = 1;
        int totalProcessed = 0;
        int totalSuccess = 0;
        int totalFailed = 0;
        int totalPageFailed = 0;

        log.info("开始自定义产品系列数据迁移，每页处理 {} 条记录", pageSize);

        QueryWrapper<HzProductSeries> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("del_flag", "0", "2");
        queryWrapper.in("audit_flag", "0", "2");
        queryWrapper.isNotNull("exhibitor_id");
        // 用于缓存展商ID映射关系
        Map<String, IdMapping> exhibitorIdMap = new ConcurrentHashMap<>();

        List<HzProductSeries> hzProductSeriesList = null;
        do {
            try {
                Page<HzProductSeries> page = new Page<>(pageNum, pageSize);
                hzProductSeriesList = hzProductSeriesMapper.selectPage(page, queryWrapper).getRecords();
                if (CollectionUtil.isEmpty(hzProductSeriesList)) {
                    log.info("分页查询完成，没有更多数据，共处理 {} 页", pageNum - 1);
                    break;
                }

                totalProcessed += hzProductSeriesList.size();
                log.info("开始处理第 {} 页数据，当前页记录数: {}", pageNum, hzProductSeriesList.size());

                int pageSuccess = 0;
                int pageFailed = 0;

                // 处理当前页的所有记录
                for (HzProductSeries oldHzProductSeries : hzProductSeriesList) {
                    try {
                        HzProductSeriesSlave newHzProductSeriesSlave = modelMapper.map(oldHzProductSeries, HzProductSeriesSlave.class);

                        String exhibitorId = oldHzProductSeries.getExhibitorId();
                        if (StringUtils.isEmpty(exhibitorId)) {
                            throw new RuntimeException("产品系列ID为空，数据ID: " + oldHzProductSeries.getId());
                        }

                        // 使用缓存获取展商ID映射
                        IdMapping idMapping = exhibitorIdMap.computeIfAbsent(exhibitorId,
                                key -> iIdMappingService.getById(key));

                        if (idMapping == null) {
                            throw new RuntimeException("未找到展商ID映射关系，exhibitorId: " + exhibitorId);
                        }

                        // 设置展商id
                        newHzProductSeriesSlave.setUserId(idMapping.getUserId());

                        // 逐条插入并立即获取ID
                        boolean insertSuccess = hzProductSeriesSlaveService.save(newHzProductSeriesSlave);

                        if (insertSuccess) {
                            // 处理数据迁移后id映射
                            HzProductServicesIdMapping idMappingEntity = new HzProductServicesIdMapping();
                            idMappingEntity.setHzProductServicesId(oldHzProductSeries.getId());
                            idMappingEntity.setNewHzProductServicesId(newHzProductSeriesSlave.getId());

                            // 保存ID映射关系
                            boolean mappingSaved = hzProductServicesIdMappingService.save(idMappingEntity);

                            if (mappingSaved) {
                                pageSuccess++;
                                totalSuccess++;
                                log.info("数据迁移成功 - 原始ID: {}, 新ID: {}",
                                        oldHzProductSeries.getId(),
                                        newHzProductSeriesSlave.getId());
                            } else {
                                pageFailed++;
                                totalFailed++;
                                log.error("ID映射保存失败 - 原始ID: {}, 新ID: {}",
                                        oldHzProductSeries.getId(),
                                        newHzProductSeriesSlave.getId());
                            }
                        } else {
                            pageFailed++;
                            totalFailed++;
                            log.error("单条插入失败 - 展商ID: {}, 原始ID: {}",
                                    newHzProductSeriesSlave.getUserId(),
                                    oldHzProductSeries.getId());
                        }
                    } catch (Exception e) {
                        pageFailed++;
                        totalFailed++;
                        log.error("处理单条记录失败 - 数据ID: {}, 错误信息: {}",
                                oldHzProductSeries.getId(), e.getMessage(), e);
                    }
                }

                log.info("第 {} 页数据处理完成 - 成功: {}, 失败: {}", pageNum, pageSuccess, pageFailed);
                pageNum++;

            } catch (Exception e) {
                totalPageFailed++;
                log.error("处理第 {} 页数据失败，错误信息: {}", pageNum, e.getMessage(), e);
                pageNum++; // 跳过当前页继续处理下一页
            }
        } while (hzProductSeriesList != null && hzProductSeriesList.size() == pageSize);

        log.info("产品系列数据迁移完成！总处理记录数: {}, 成功: {}, 失败: {}, 失败页数: {}",
                totalProcessed, totalSuccess, totalFailed, totalPageFailed);
    }
}
